<style lang="scss" scoped>
</style>

<template>
  <div class="table">
    <el-table
      :data="list.slice((currpage - 1) * pagesize, currpage * pagesize)"
      @row-click="rowClick"
      :row-class-name="rowClassName"
      border
    >
      <template v-for="item in column">
        <el-table-column
          :prop="item.prop"
          :label="item.label"
          :key="item.prop"
          align="center"
          :min-width="item.minWidth"
          v-if="!item.slot"
        />
        <el-table-column
          :label="item.label"
          :key="item.prop"
          align="center"
          :min-width="item.minWidth"
          v-else
        >
          <template slot-scope="scope">
            <slot :row="scope.row" :prop="item.prop" :column="item" />
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next, sizes, total, jumper"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pagesize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script>
export default {
  name: 'TableCom',
  data() {
    return {
      list: [],
      pagesize: 20,
      total: 0,
      currpage: 1
    }
  },
  props: {
    api: String,
    column: Array,
    params: Object,
    config: Object
  },
  methods: {
    rowClick(row) {
      this.$emit('row-click', row)
    },
    rowClassName({row, rowIndex}) {
      //把每一行的索引放进row.id
      row.id = rowIndex
    },
    handleCurrentChange(cpage) {
      this.currpage = cpage
      this.fetch()
    },
    handleSizeChange(psize) {
      this.pagesize = psize
      this.fetch()
    },
    async fetch(currpage = 1) {
      if (currpage === 1) this.currpage = 1
      const { data } = await this.$axios.post(this.api, {
        ...this.params,
        pageNo: this.currpage,
        pageSize: this.pagesize
      })
      if (data?.list?.length) {
        this.list = data.list
        console.log(data.list)
        this.total = data.total
        if (this.config.getList) this.config.getList(data.list)
      }
    }
  }
}
</script>